/*
 * Copyright (c) 2015-2025 by HRT All rights reserved
 */
package net.xinshi.commons.log;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.nio.charset.Charset;

public class BytesLoggingWrapper {
	private static final Logger logger = LogManager.getLogger(BytesLoggingWrapper.class);
	private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
	private byte[] wrappedBytes;
	private String charset;

	private BytesLoggingWrapper(byte[] bytes, String charset) {
		this.wrappedBytes = bytes;
		this.charset = charset;
	}

	public static BytesLoggingWrapper wrap(byte[] bytes) {
		return new BytesLoggingWrapper(bytes, "UTF-8");
	}

	public static BytesLoggingWrapper wrap(byte[] bytes, String charset) {
		return new BytesLoggingWrapper(bytes, charset);
	}

	public byte[] getWrappedBytes() {
		return wrappedBytes;
	}

	@Override
	public String toString() {
		if (null == wrappedBytes || 0 == wrappedBytes.length) {
			return "";
		}

		String str = null;
		try {
			Charset cs = null;
			if (null == charset || 0 == charset.length()) {
				cs = DEFAULT_CHARSET;
			} else {
				cs = Charset.forName(charset);
			}
			str = new String(wrappedBytes, cs);
		} catch (Exception e) {
			logger.warn("Cannot decode the byte array to string, error: {}", e.getMessage(), e);
		}

		if (null == str) {
			str = "";
		} else {
			str = str.trim().replaceAll("[\r\n]", "").replaceAll("\t+", " ");
		}
		return str;
	}

}
